package com.quiz.bis.util.pdf;

import com.quiz.common.utils.uuid.UUID;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.scilab.forge.jlatexmath.TeXConstants;
import org.scilab.forge.jlatexmath.TeXFormula;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

public class FormulaUtils {
    private static final int FORMULA_FONT_SIZE = 12;
    private static final Color FORMULA_COLOR = Color.BLACK;
    private static final Color FORMULA_BACKGROUND = Color.WHITE;

    public static void addFormulaToParagraph(XWPFParagraph paragraph, String latex) {
        try {
            TeXFormula formula = new TeXFormula(latex);
            BufferedImage image = (BufferedImage)formula.createBufferedImage(
                    TeXConstants.STYLE_DISPLAY,
                    FORMULA_FONT_SIZE,
                    FORMULA_COLOR,
                    FORMULA_BACKGROUND);

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ImageIO.write(image, "png", bos);
            byte[] imageData = bos.toByteArray();

            XWPFRun run = paragraph.createRun();
            run.addPicture(
                    new ByteArrayInputStream(imageData),
                    XWPFDocument.PICTURE_TYPE_PNG,
                    "formula_" + UUID.randomUUID() + ".png",
                    Units.toEMU(image.getWidth()),
                    Units.toEMU(image.getHeight()));
        } catch (Exception e) {
            // 备用方案：显示LaTeX代码
            XWPFRun run = paragraph.createRun();
            run.setText(" [" + latex + "] ");
            run.setColor("FF0000");
        }
    }
}
